package com.jt.www.common.service.impl;

import com.jt.www.common.service.AttrConfigService;
import com.jt.www.dao.mapper.attrconfig.AttrConfigMapper;
import com.jt.www.domain.enums.common.AttrConfigTypeEnum;
import com.jt.www.domain.po.AttrConfig;
import com.jt.www.util.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.Date;
import java.util.List;

/**
 * 全局参数配置
 * Created by shaoyn on 2020/08/07.
 */
@Service
public class AttrConfigServiceImpl implements AttrConfigService {

    public static final Logger log = LoggerFactory.getLogger(AttrConfigServiceImpl.class);
    private static final String OFFLINE_USER_DEFAULT_NO = "1000";
    @Autowired
    private AttrConfigMapper attrConfigMapper;

    @Override
    public String createOfflineUserCode() {

        AttrConfig query = new AttrConfig();
        query.setType(AttrConfigTypeEnum.OFFLINE_REGISTER_NO.getType());
        List<AttrConfig> attrConfigs = attrConfigMapper.select(query);

        //如果上生产时没有配置  自动生成一条，这块先不用考虑并发，因为基本没有可能触发这一并发
        if (CollectionUtils.isEmpty(attrConfigs)) {
            query.setValue(OFFLINE_USER_DEFAULT_NO);
            query.setRemark(AttrConfigTypeEnum.OFFLINE_REGISTER_NO.getRemark());
            query.setUpdateTime(new Date());
            attrConfigMapper.insert(query);
            return createOfflineUserCode();
        }

        AttrConfig attrConfig = attrConfigs.get(0);

        //如果当时时间与数据库最后更新时间是同一天，当前值为数据的值，否则取默认值
        String newValue = DateUtils.isSameDay(attrConfig.getUpdateTime(), new Date()) ?
                attrConfig.getValue() : OFFLINE_USER_DEFAULT_NO;

        String nextValue = String.valueOf(Integer.parseInt(newValue) + 1);

        Weekend<AttrConfig> updateQuery = Weekend.of(AttrConfig.class);
        WeekendCriteria<AttrConfig, Object> managerCriteria = updateQuery.weekendCriteria();
        managerCriteria.andEqualTo(AttrConfig::getId, attrConfig.getId());
        managerCriteria.andEqualTo(AttrConfig::getValue, attrConfig.getValue());
        managerCriteria.andEqualTo(AttrConfig::getUpdateTime, attrConfig.getUpdateTime());

        AttrConfig update = new AttrConfig();
        update.setValue(nextValue);
        update.setUpdateTime(new Date());

        //乐观锁控制
        if (1 == attrConfigMapper.updateByExampleSelective(update, updateQuery)) {
            return "E_" + DateUtils.format(new Date(), DateUtils.DATE_FORMAT_YYMMDD) + "_" + nextValue;
        }

        //更新失败重新查询
        return createOfflineUserCode();
    }

}
